package com.example.hospital.mapper;

import com.example.hospital.domain.entity.Doctor;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface DoctorMapper {
    @Select("SELECT * FROM doctor WHERE doctor_id = #{doctorId}")
    Doctor findById(@Param("doctorId") Long doctorId);

    @Select("SELECT * FROM doctor WHERE phone = #{phone}")
    Doctor findByPhone(@Param("phone") String phone);

    @Insert("INSERT INTO doctor (name, gender, phone, password, department_id, position_id, intro, create_time) VALUES (#{name}, #{gender}, #{phone}, #{password}, #{departmentId}, #{positionId}, #{intro}, NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "doctorId")
    int insert(Doctor doctor);

    @Update("UPDATE doctor SET name=#{name}, gender=#{gender}, phone=#{phone}, department_id=#{departmentId}, position_id=#{positionId}, intro=#{intro} WHERE doctor_id=#{doctorId}")
    int update(Doctor doctor);

    @Select({
            "<script>",
            "SELECT * FROM doctor",
            "<where>",
            "  <if test=\"name != null and name != ''\"> AND name LIKE CONCAT('%', #{name}, '%') </if>",
            "  <if test=\"departmentId != null\"> AND department_id = #{departmentId} </if>",
            "  <if test=\"positionId != null\"> AND position_id = #{positionId} </if>",
            "</where>",
            "ORDER BY create_time DESC",
            "LIMIT #{limit} OFFSET #{offset}",
            "</script>"
    })
    List<Doctor> list(@Param("name") String name,
                      @Param("departmentId") Long departmentId,
                      @Param("positionId") Long positionId,
                      @Param("limit") int limit,
                      @Param("offset") int offset);

    @Select({
            "<script>",
            "SELECT COUNT(1) FROM doctor",
            "<where>",
            "  <if test=\"name != null and name != ''\"> AND name LIKE CONCAT('%', #{name}, '%') </if>",
            "  <if test=\"departmentId != null\"> AND department_id = #{departmentId} </if>",
            "  <if test=\"positionId != null\"> AND position_id = #{positionId} </if>",
            "</where>",
            "</script>"
    })
    long count(@Param("name") String name,
               @Param("departmentId") Long departmentId,
               @Param("positionId") Long positionId);
}